//
//  PersonOKListViewController.m
//  WisdomZhuHai
//
//  Created by JasonLee on 15/2/1.
//  Copyright (c) 2015年 wyd. All rights reserved.
//

#import "PersonOKListViewController.h"
#import "DVSwitch.h"
#import "TransforController.h"
#import "EmptyViewController.h"

@interface PersonOKListViewController (){
    PullTableView *_tableView;
    NSMutableArray *_order;
    NSMutableArray *_orderCells;
    int currRow;
    UILabel *lbFoundNoOrders;
}
@property (nonatomic,assign) int currentIndex;

@property (nonatomic,strong)NSMutableArray *dataInReturn;

@property (nonatomic, assign) int page_current;//储存当前所选择的所要显示的ok码列表的ok码性质（全部=0、未使用=1、已使用=2）

@property (nonatomic, strong) DVSwitch *topSelectMenu;

//@property(nonatomic, assign) int status_current;

@end

@implementation PersonOKListViewController

//Bable-Note
//- (void)viewDidLoad {
//    [super viewDidLoad];
//    // Do any additional setup after loading the view from its nib.
//    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
//    NSLog(@"Loading PersonOKListViewController;");
//    
//    self.currentIndex = 0;
//    self.page_current = 0;
//    //    self.status_current = 0;
//    //[self initData];
//    [self setEnableLoadMore:YES];
//    self.pullTableViewDelegate = self;
//    self.navigationItem.title = @"OK码列表";
//    CGRect screenRect = [UIScreen mainScreen].bounds;
//    CGSize screenSize = screenRect.size;
//    [self.view setFrame:[UIScreen mainScreen].bounds];
//    //_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height - 60)];
//    self.tableView.frame = CGRectMake(0, HEIGHT_MENU_BAR, screenSize.width, self.view.bounds.size.height - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR - HEIGHT_MENU_BAR);
//    _tableView = self.tableView;
//    //NSLog(@"==>>PersonOrderList-->>viewDidLoad||_tableView:%f", _tableView.frame.size.height);
//    _tableView.delegate = self;
//    _tableView.dataSource = self;
//    _tableView.tableFooterView = [[UIView alloc]init];
//    
//    //    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTableviewCellLongPressed:)];
//    //    longPress.minimumPressDuration = 1.0;
//    //    [_tableView addGestureRecognizer:longPress];
//    [self.view addSubview:_tableView];
//    UIView *view_navagationBar = [[UIView alloc]initWithFrame:CGRectMake(0, -65, 320, 1)];
//    view_navagationBar.backgroundColor = [Common colorWithRGB:0x18aaf6];
//    [self.view addSubview:view_navagationBar];
//    [self initMenuWithArray];
//    //    self.navigationController.navigationBar.backgroundColor  = [Common colorWithRGB:0x18aaf6];
//    [self getCouponList];
//}

//Bable-
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSLog(@"childViewControllers:%@", self.navigationController.childViewControllers);
    NSLog(@"Loading PersonOKListViewController;");
    
    self.currentIndex = 0;
    self.page_current = 0;
    //    self.status_current = 0;
    //[self initData];
    [self setEnableLoadMore:YES];
    self.pullTableViewDelegate = self;
    self.navigationItem.title = @"OK码列表";
    CGRect screenRect = [UIScreen mainScreen].bounds;
    CGSize screenSize = screenRect.size;
    [self.view setFrame:[UIScreen mainScreen].bounds];
    //_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height - 60)];
//    self.tableView.frame = CGRectMake(0, HEIGHT_MENU_BAR, screenSize.width, self.view.bounds.size.height - HEIGHT_NAVIGATION_BAR - HEIGHT_STATUS_BAR - HEIGHT_MENU_BAR);//Bable-Note
        self.tableView.frame = CGRectMake(0, 0, screenSize.width, self.view.bounds.size.height - 0 - 0 - 0);//各UI尺寸控制器
    _tableView = self.tableView;
    //NSLog(@"==>>PersonOrderList-->>viewDidLoad||_tableView:%f", _tableView.frame.size.height);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    //    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleTableviewCellLongPressed:)];
    //    longPress.minimumPressDuration = 1.0;
    //    [_tableView addGestureRecognizer:longPress];
    [self.view addSubview:_tableView];
    UIView *view_navagationBar = [[UIView alloc]initWithFrame:CGRectMake(0, -65, 320, 1)];
    view_navagationBar.backgroundColor = [Common colorWithRGB:0x18aaf6];
//    [self.view addSubview:view_navagationBar];
//    [self initMenuWithArray];
    [self getCouponList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (void)initData:(NSArray *)array{
//    //NSString *path = [[NSBundle mainBundle] pathForResource:@"PersonOrder" ofType:@"plist"];
//    //NSArray *array = [NSArray arrayWithContentsOfFile:path];
//    if (_order.count <= 0){
//        self->_order = [[NSMutableArray alloc]init];}
//    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        [self->_order addObject:[OrderModel statusWithDictionary:obj]];
//        //NSLog(@"==>>PersonOrderList-->>initData||model:%@", [[_order objectAtIndex:idx] getOrder]);
//    }];
//    //NSLog(@"==>>PersonOrderList-->>initData||_order:%@",_order);
//}

//Bable-Note
//- (void)initMenuWithArray{
//    if(self.topSelectMenu == nil){
//        self.topSelectMenu = [DVSwitch switchWithStringsArray:[NSArray arrayWithObjects:@"全部",@"未使用",@"已使用", nil]];
//        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
//        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
//        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
//        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
//        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
//        self.topSelectMenu.cornerRadius = 5;
//        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
//        [self.view addSubview:self.topSelectMenu];
//    }
//}
//Bable-
- (void)initMenuWithArray{
    if(self.topSelectMenu == nil){
        self.topSelectMenu = [DVSwitch switchWithStringsArray:[NSArray arrayWithObjects:@"全部",@"未使用",@"已使用", nil]];
        self.topSelectMenu.frame = CGRectMake(0, 0, 320, 35);
        self.topSelectMenu.backgroundColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.sliderColor = [UIColor colorWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1];
        self.topSelectMenu.labelTextColorInsideSlider = [UIColor colorWithRed:20/255.0 green:180/255.0 blue:220/255.0 alpha:1];
        self.topSelectMenu.labelTextColorOutsideSlider = [UIColor blackColor];
        self.topSelectMenu.cornerRadius = 5;
        [self.topSelectMenu addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:self.topSelectMenu];
    }
}


- (void)valueChanged:(id)sender{//更换列表tag，刷新tableview
    DVSwitch* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %d", __FUNCTION__, __LINE__, segmentedControl.
          selectedIndex);
    
    if(self.page_current != segmentedControl.selectedIndex){
        self.page_current = segmentedControl.selectedIndex;
        [self pullTableViewDidTriggerRefresh:self.tableView];
        //        self.status_current = segmentedControl.selectedIndex;
    }
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - Protocol request
- (void)getCouponList//调用按所要求的ok码状态等属性获取ok码列表的协议
{
    //[[ProtocolManager shareInstance] getStoreType:self selector:@selector(getOrderListCallback:)];
    //    [[ProtocolManager shareInstance] getOrderList:[ProtocolManager shareInstance].loginName pageIndex:[[NSString alloc]initWithFormat:@"%i",_currentIndex + 1] target:self selector:@selector(getOrderListCallback:)];
    //    [TransforController statusLoadingBar];
    [[Common shareInstance]showLoadingViewWithMessage:@"加载中"];
//    [[ProtocolManager shareInstance] getOkListWithStatus:self.page_current andPage:_currentIndex + 1 target:self selector:@selector(getCounponListCallback:)];//Bable-Note
    NSLog(@"%d !!!!!!!!!!!!!!!!!!!!!!!!!!!",self.page_current );
    self.page_current = 1;//在刷新tableView时，令该属性恒等于1，这样tableview只会显示未使用的ok码的列表
        [[ProtocolManager shareInstance] getOkListWithStatus:self.page_current andPage:_currentIndex + 1 target:self selector:@selector(getCounponListCallback:)];
    
    
}

#pragma mark - Protocol call back
- (void)getCounponListCallback:(NSDictionary*)dic
{
    NSLog(@"%s || dic:%@", __FUNCTION__, dic);
    if ((dic[P_RESULT] == [NSNull null]) ) {
        [self resetPullTableViewState];
        return;
    }
    if (self.currentIndex == 0) {//全部OK券
        self.dataInReturn = [NSMutableArray array];
    }
    NSArray* orderList;
    if(![[Common valueForKey:P_RESULT dic:dic] isKindOfClass:[NSArray class]]){
        orderList = [[NSArray alloc]init];//全部OK券
    }else{
        orderList = [Common valueForKey:P_RESULT dic:dic];
    }
    if ([orderList isKindOfClass:[NSArray class]]) {
        [self.dataInReturn addObjectsFromArray:orderList];//全部OK券
        self.currentIndex++;
    }
    if(self.dataInReturn.count > 0){
        if (orderList.count < 15) {
            [self setEnableLoadMore:NO];
        }
        else {
            [self setEnableLoadMore:YES];
        }
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||orderList:%@", orderList);
        //NSLog(@"==>>PersonOrderList-->>getOrderListCallBack||dataInReturn:%@", _dataInReturn);
        [self resetPullTableViewState];
        //      if(lbFoundNoOrders != nil){
        [lbFoundNoOrders removeFromSuperview];
    }else{
        if(lbFoundNoOrders == nil){
            lbFoundNoOrders = [[UILabel alloc] initWithFrame:CGRectMake(0, 120, 320, 30)];
            lbFoundNoOrders.textColor = [UIColor grayColor];
            lbFoundNoOrders.text = @"还没有OK码！";
            lbFoundNoOrders.textAlignment = UITextAlignmentCenter;
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
            [self setEnableLoadMore:NO];
        }else{
            [_tableView.tableFooterView addSubview:lbFoundNoOrders];
        }
    }
    [_tableView reloadData];
    [[Common shareInstance]stopLoadingView];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    //NSLog(@"%lu", (unsigned long)_order.count);
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataInReturn.count;
}

//ok码状态显示
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = nil;
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    NSDictionary *dic_temp = [self.dataInReturn objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%d. %@",indexPath.row + 1, [Common valueForKey:@"oksn" dic:dic_temp]];
    UILabel *lb_detail = [[UILabel alloc]initWithFrame:CGRectMake(cell.frame.size.width - 100, 13, 80, cell.frame.size.height - 15)];
    if([[Common valueForKey:@"useStatus" dic:dic_temp]isEqualToString:@"0"]){
        lb_detail.backgroundColor = [Common colorWithRGB:0x18aaf6];
        lb_detail.text = @"未使用";
    }else if([[Common valueForKey:@"useStatus" dic:dic_temp]isEqualToString:@"1"]){
        lb_detail.backgroundColor = [Common colorWithRGB:0xf6f6f6];
        lb_detail.text = @"已使用";
    }else{
        lb_detail.backgroundColor = [TransforController getColorWithRed:255 andGreen:208 andBlue:0 andAlpha:1];
        lb_detail.text = @"退款中";
    }
    lb_detail.textColor = [UIColor whiteColor];
    lb_detail.textAlignment = UITextAlignmentCenter;
    [cell addSubview:lb_detail];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

//单击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        NSDictionary *dic = _dataInReturn[indexPath.row];
        EmptyViewController *QRCodeCtrl = [[EmptyViewController alloc] initWithFrame:self.view.bounds];
        QRCodeCtrl.isOKCoupon = YES;
        QRCodeCtrl.OKCoupon = [Common valueForKey:P_OKSN dic:dic];
        [self.navigationController pushViewController:QRCodeCtrl animated:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}


#pragma mark - PullTableViewDelegate
- (void)pullTableViewDidTriggerRefresh:(PullTableView*)pullTableView
{
    NSLog(@"refresh...");
    self.currentIndex = 0;
    [self setPullTableIsLoadMore:YES];
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self getCouponList];
}

-(void)pullTableViewDidTriggerLoadMore:(PullTableView *)pullTableView
{
    NSLog(@"loadMore...");
    [self getCouponList];
}

- (void)resetPullTableViewState
{
    [self setPullTableIsRefreshing:NO];
    [self setPullTableIsLoadMore:NO];
}

@end
